"use client";

import { nanoid } from "nanoid";
import { useCallback, useRef, useState } from "react";

import { useAutoScrollToBottom } from "~/components/hooks/useAutoScrollToBottom";
import { ScrollArea } from "~/components/ui/scroll-area";
import { TooltipProvider } from "~/components/ui/tooltip";
import { sendMessage, useInitTeamMembers, useStore } from "~/core/store";
import { cn } from "~/core/utils";

import { AppHeader } from "./_components/AppHeader";
import { InputBox } from "./_components/InputBox";
import { MessageHistoryView } from "./_components/MessageHistoryView";

export default function HomePage() {
  const scrollAreaRef = useRef<HTMLDivElement>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  const messages = useStore((state) => state.messages);
  const responding = useStore((state) => state.responding);

  const [articlePrompt, setArticlePrompt] = useState({
    style: "基础风格（这个名称无意义）",
    title: "简洁表达\n长度控制在10字以内", 
    content: "保证学术严谨性\n区分已验证事实与行业推测\n字数在200至300个汉字\n根据内容适当插入个人见解和分析，增强文章的独特性\n避免断过过于简单枯燥，适当增加描述",
    host: ""
  });

  const handleSendMessage = useCallback(
    async (
      content: string,
      config: { 
        deepThinkingMode: boolean; 
        searchBeforePlanning: boolean;
      },
    ) => {
      const abortController = new AbortController();
      abortControllerRef.current = abortController;

      await sendMessage(
        {
          id: nanoid(),
          role: "user",
          type: "text",
          content,
        },
        {
          ...config,
          articlePrompt
        },
        { abortSignal: abortController.signal },
      );
      abortControllerRef.current = null;
    },
    [articlePrompt],
  );

  const handlePromptChange = useCallback((field: string, value: string) => {
    setArticlePrompt(prev => ({
      ...prev,
      [field]: value
    }));
  }, []);

  useInitTeamMembers();
  useAutoScrollToBottom(scrollAreaRef, responding);

  return (
    <TooltipProvider delayDuration={150}>
      <ScrollArea className="h-screen w-full" ref={scrollAreaRef}>
        <div className="flex min-h-screen flex-col items-center">
          <header className="sticky top-0 right-0 left-0 z-10 flex h-16 w-full items-center px-4 backdrop-blur-sm">
            <AppHeader />
          </header>
          <main className="w-full flex-1 px-4 pb-48 relative">
            <div className="w-[calc(65%-24px)]" style={{ padding: '100px' }}>
              <div className="flex flex-col items-center justify-center h-full">
                <MessageHistoryView
                  messages={messages}
                  loading={responding}
                />
              </div>
            </div>
            <div className="fixed top-16 right-0 w-[30vw] h-[calc(60vh)] flex flex-col gap-4 p-6 bg-white shadow-lg border-l border-gray-200 z-10">
              <div className="space-y-1">
                <label className="text-sm font-medium text-gray-700">写作风格（style）</label>
                <input
                  type="text"
                  className="w-full border border-gray-200 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                  placeholder="输入风格|赛道"
                  value={articlePrompt.style}
                  onChange={(e) => handlePromptChange('style', e.target.value)}
                />
              </div>
              <div className="flex-2 space-y-1">
                <label className="text-sm font-medium text-gray-700">标题要求（title）</label>
                <textarea
                  className="w-full h-full min-h-[100px] border border-gray-200 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                  placeholder="输入标题要求"
                  value={articlePrompt.title}
                  onChange={(e) => handlePromptChange('title', e.target.value)}
                />
              </div>
              <div className="flex-8 space-y-1">
                <label className="text-sm font-medium text-gray-700">正文要求（content）</label>
                <textarea
                  className="w-full h-full min-h-[150px] border border-gray-200 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                  placeholder="输入正文要求"
                  value={articlePrompt.content}
                  onChange={(e) => handlePromptChange('content', e.target.value)}
                />
              </div>
              <div className="flex-5 space-y-1">
                <label className="text-sm font-medium text-gray-700">参考链接（host）</label>
                <textarea
                  className="w-full h-full min-h-[150px] border border-gray-200 rounded-lg px-4 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                  placeholder="输入参考链接"
                  value={articlePrompt.host}
                  onChange={(e) => handlePromptChange('host', e.target.value)}
                />
              </div>
            </div>
          </main>
          <footer
            className={cn(
              "fixed bottom-4 transition-transform duration-500 ease-in-out",
              messages.length === 0
                ? "w-[640px] translate-y-[-34vh]"
                : "w-page",
            )}
          >
            {messages.length === 0 && (
              <div className="flex w-[640px] translate-y-[-32px] flex-col">
                <h3 className="mb-2 text-center text-3xl font-medium">
                  👋 Hello, there!
                </h3>
                <div className="px-4 text-center text-lg text-gray-400">
                  <a
                    href="https://135editor.com"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="underline hover:text-blue-600"
                  >
                    135manus
                  </a>
                  , 这是一个只能写文章的测试demo啊啊啊啊，不能生成ppt svg, 你传个标题、概念、梦都行！！
                </div>
              </div>
            )}
            <div className="flex flex-col overflow-hidden rounded-[24px] border bg-white shadow-lg">
              <InputBox
                size={messages.length === 0 ? "large" : "normal"}
                responding={responding}
                onSend={handleSendMessage}
                onCancel={() => {
                  abortControllerRef.current?.abort();
                  abortControllerRef.current = null;
                }}
              />
            </div>
            <div className="w-page absolute bottom-[-32px] h-8 backdrop-blur-xs" />
          </footer>
        </div>
      </ScrollArea>
    </TooltipProvider>
  );
}
